package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogItemParser;
import lombok.val;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Pattern;

public class LogItemParserCxmImpl implements LogItemParser {

    @Override
    public Optional<LogItem> parse(String line) {
        String ip="",time="",request="",status="",bytes="",referer="",ua="";
        final Pattern LOG_PATTERN = Pattern.compile("(?<ip>\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+[\\w\\-]+\\s+[\\w\\-]+\\s+\\[(?<dt>\\d+/\\w+/\\d+:\\d+:\\d+:\\d+\\s+\\+\\d+)]\\s+\"(?<request>.*)\"\\s+(?<status>\\d+)\\s+(?<sent>\\d+)\\s+\"(?<referer>[^\"]+)\"\\s+\"(?<ua>[^\"]+)\"");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        val m = LOG_PATTERN.matcher(line);
        if(m.matches()){
             ip=m.group("ip");
             time=m.group("dt");
             request=m.group("request");
             status=m.group("status");
             bytes=m.group("sent");
             referer=m.group("referer");
             ua=m.group("ua");
        }
        String [] parseArr=parseRequest(request);
        String method=parseArr[0];
        String path=parseArr[1];
        String protocol=parseArr[2];

        return Optional.of(new LogItem(ip,LocalDateTime.parse(time,formatter),request,method,path,null,protocol,Integer.parseInt(status),Long.parseLong(bytes),referer,ua));
    }

    public String[] parseRequest(String request){
        final Pattern REQUEST_PATTERN = Pattern.compile("(?<method>\\w+)\\s+(?<url>[^ ]+)\\s+(?<protocol>[^ ]+)");
        String method,url,protocol;
        val m1=REQUEST_PATTERN.matcher(request);
        String path;
        if(m1.matches()){
            method=m1.group("method");
            url=m1.group("url");
            protocol=m1.group("protocol");
            if(url.contains("?")){
                path=url.substring(0,url.indexOf("?"));
            }else {
                path=url;
            }
            return new String[]{method,path,protocol};
        }
        return new String[]{null,null,null};
    }

}
